﻿//--------------------------------------------------------------------------------------------------------------------------------------------------------
// <copyright file="EmailTransport.cs">
//     Copyright © 2010 Oli Francis
//     This source code is subject to the terms and conditions of the MIT license. A copy of the license can be found in the license.txt 
//     file at the root of this distribution. By using this source code in any fashion, you are agreeing to be bound by the terms of the MIT License. 
//     You must not remove this notice from the software.
// </copyright>
// <author>Oli</author>
//-------------------------------------------------------------------------------------------------------------------------------------------------------

namespace TeamBrain.Domain.Services.Email
{
    using System;
    using System.Net;
    using System.Net.Mail;
    using System.Net.Mime;

    using TeamBrain.Domain.Model;

    /// <summary>
    /// Exposes functionality around sending an email
    /// </summary>
    public class EmailTransport : IEmailTransport
    {
        /// <summary>
        /// Sends the specified email.
        /// </summary>
        public void Send(SystemEmail email)
        {
            var message = new MailMessage
                {
                    From = new MailAddress(email.FromAddress, email.FromDisplayName),
                    Subject = email.Subject
                };

            message.To.Add(new MailAddress(email.ToAddress, email.ToDisplayName));
            
            if (!String.IsNullOrEmpty(email.PlainTextBody))
            {
                message.Body = email.PlainTextBody;
                message.IsBodyHtml = false;
            }

            if (!String.IsNullOrEmpty(email.HtmlBody))
            {
                var mimeType = new System.Net.Mime.ContentType("text/html");
                var alternate = AlternateView.CreateAlternateViewFromString(email.HtmlBody, mimeType);
                message.AlternateViews.Add(alternate);
            }

            var client = new SmtpClient();
            client.Send(message);
        }
    }
}